<?php

namespace app\service\common;

class BankCard
{

    /**
     * 银行卡类型
     */
    private $CardType = [
        1 => '借记卡',
        2 => '贷记卡',
        3 => '准贷记卡',
        4 => '预付费卡',
    ];
    public function get_bank_card($card) {
        if (empty($card)) {
            return errorMessage("银行卡号为空");
        }
        $length = mb_strlen($card);
        if ($length > 19 || $length < 14) {
           return errorMessage("银行卡号格式错误");
        }
        $data = [];
        for ($i=4; $i <=10 ; $i++) {
            $key = substr($card, 0, $i);
            $arr =config('bank_card');
            if (isset($arr[$key])) {
                $data = $arr[$key];
                break;
            }
        }
        if (empty($data)) {
            return errorMessage("归属银行识别失败，更新归属地址库");
        }
        return [
            'bank_name' => $data[0],
            'card_type_name' => $this->CardType[$data[2]],
            'card_type_name2' => $data[1],
            'card_type' => $data[2],
            'is_luhm' => $this->Luhm($card)
        ];
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 16 OR 19位
     * @param string $cardId
     * @return bool
     */
    private function Luhm(string $cardId) {
        $arr_no = str_split($cardId);
        $last_n = $arr_no[count($arr_no)-1];
        krsort($arr_no);
        $i = 1;
        $total = 0;
        foreach ($arr_no as $n){
            if($i%2==0){
                $ix = $n*2;
                if($ix>=10){
                    $nx = 1 + ($ix % 10);
                    $total += $nx;
                }else{
                    $total += $ix;
                }
            }else{
                $total += $n;
            }
            $i++;
        }
        $total -= $last_n;
        $total *= 9;
        if($last_n == ($total%10)){
            return true;
        }
        return false;
    }
}
